﻿//
// Copyright 2024 Exhunter Technology Co.Ltd2.
//

using System;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace X18.Framework.Core.Serialize
{
    public class JsonSerializer
    {
        public static byte[] SerializeToByte<T>(T value)
        {
            string buffer = SerializeToString<T>(value);
            byte[] result = Encoding.BigEndianUnicode.GetBytes(buffer);
            return result;
        }

        public static string SerializeToString<T>(T value)
        {
            string result = JsonConvert.SerializeObject(value);
            return result;
        }

        public static T DeserializeFromByte<T>(byte[] data)
        {
            string buffer = Encoding.BigEndianUnicode.GetString(data, 0, data.Length);
            T result = DeserializeFromString<T>(buffer);
            return result;
        }

        public static T DeserializeFromString<T>(string data)
        {
            T result = JsonConvert.DeserializeObject<T>(data);
            return result;
        }
    }

    /// <summary>
    /// 日期格式化
    /// </summary>
    public class JsonDateTimeFormat : IsoDateTimeConverter
    {
        /// <summary>
        /// 日期格式
        /// </summary>
        public JsonDateTimeFormat() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; }
    }

    /// <summary>
    /// 日期格式化
    /// </summary>
    public class JsonDateFormat : IsoDateTimeConverter
    {
        /// <summary>
        /// 日期格式
        /// </summary>
        public JsonDateFormat() { DateTimeFormat = "yyyy-MM-dd"; }
    }
}
